#include<func.h>
#define N 100
typedef struct{
    int tickets;
    pthread_mutex_t mutex;
}data_t;

void * saler1(void *p)
{
    data_t* d=(data_t*)p;
    while(1)
    {
        pthread_mutex_lock(&d->mutex);
        if(d->tickets>0)
        {
            printf("saler1 start sale %d\n",d->tickets);
            d->tickets--;
            pthread_mutex_unlock(&d->mutex);
            printf("saler1 finish sale %d\n",d->tickets);
        }
        else{
            pthread_mutex_unlock(&d->mutex);
            break;
        }
    }
}
void * saler2(void *p)
{
    data_t* d=(data_t*)p;
    while(1)
    {
        pthread_mutex_lock(&d->mutex);
        if(d->tickets>0)
        {
            printf("saler1 start sale %d\n",d->tickets);
            d->tickets--;
            pthread_mutex_unlock(&d->mutex);
            printf("saler1 finish sale %d\n",d->tickets);
        }
        else{
            pthread_mutex_unlock(&d->mutex);
            break;
        }
    }
}
int main()
{
    data_t d;
    d.tickets=N;
    int ret=pthread_mutex_init(&d.mutex,NULL);
    THREAD_ERR_CHECK(ret,"pthread_mutex_init");
    pthread_t pthid[2];
    for(int i=0;i<2;i++)
    {
        ret=pthread_create(pthid+i,NULL,saler1,&d);
      THREAD_ERR_CHECK(ret,"pthread_create");
    }
        for(int i=0;i<2;i++)
    {
        ret=pthread_join(pthid[i],NULL);
      THREAD_ERR_CHECK(ret,"pthread_join");
    }
    printf("main thread tickets=%d\n",d.tickets);
    ret=pthread_mutex_destroy(&d.mutex);//销毁锁
    THREAD_ERR_CHECK(ret,"pthread_mutex_destroy");
    return 0;

}